<template>
  <div class='market txtcolor'>
    <!-- 顶部 -->
    <div class="tvTop ratop flex alcenter txtcolor">
      <div class="flex alcenter">
          <div :class="['ft20 symbol radius4 pointer flex alcenter',{'seBg':showMarket}]" @click="showMarket=!showMarket">
            <span>{{tradeData.symbol}}</span> 
            <p class="iconfont icon-jiantou_down seBg radius4 tc ft12 ml5 down-arrow"></p>
          </div>
				<!-- <p class="ml10 mpart white ft12 btnBg radius4">主板</p> -->
				<p class="ml15 flex alcenter">
          <span class="ft20 green">{{nowPrice || 0.00 | Fixed2}} </span> 
					<span class="ft12 txtgray pl5"> ≈ {{nowPrice*rate || 0.00 | Fixed2}} CNY</span>
        </p>
			</div>
			<ul class="flex alcenter ft12">
				<li class="ml40">
					<span class="txtgray">涨幅</span>
					<p class="green bold">{{socketData.change || '--'}}%</p>
				</li>
				<li class="ml40 tc">
					<span class="txtgray">高</span>
					<p>{{socketData.high || '0.00' | Fixed2}}</p>
				</li>
				<li class="ml40 tc">
					<span class="txtgray">低</span>
					<p>{{socketData.low || '0.00' | Fixed2}}</p>
				</li>
				<li class="ml40">
					<span class="txtgray">24H量</span>
					<p>{{socketData.volume || '0.00' | Fixed2 }}</p>
				</li>
			</ul>
		</div>
    <!-- chart -->
    <div class="chart_select toptitle ratop flex between">
      <p>Chart</p> 
    </div>
    <!-- market -->
    <div class="market_content partBg bd radius4" v-show='showMarket'>
      <div class="flex legalbox upbg bdb ratop txtgray">
        <p v-for="(item,index) in quoList" :class="['pointer',{'actives':current==index}]" @click="changeLegal(index,item.name)">{{item.name}}</p>
      </div>
      <div class="coinbox ft12 rbom"><!-- 筛选 -->
        <div class="flex classfity txtgray">
          <div :class="['flex alcenter',{'end':index!=0},{'w25':index==0 || index==2},{'w20':index==1},{'w30':index==3}]" v-for="(item,index) in classtify" @click="sortData(index,item.key)">
            <span>{{item.text}}</span> 
            <p class="flex column between">
              <span :class="['up',{'sort':(index===sortindex)&&direction}]"></span>
              <span :class="['down',{'sort':index===sortindex&&!direction}]"></span>
            </p>
          </div>
        </div>
        <ul class="scroll"><!-- 交易对 -->
          <li v-for="(market,index) in marketList" v-if="current==index">
            <div v-for="(item,idx) in market" class="flex coinlist alcenter bdb pointer" @click="change(item.legal_id,item.currency_id,item.legal_name,item.currency_name)">
              <p class="w25">
                <span class="iconfont icon-star0 ft14 txtgray" v-if="!item.add" @click.stop="addSelf(item.id)"></span>
                <span class="iconfont icon-star1 ft14 blue" v-else></span>
                <span class="ml5">{{item.currency_name}}/{{item.legal_name}}</span>
              </p>
              <p class="tr w20">{{item.now_price}}</p>
              <p :class="['tr','green','w25',{'red':item.change<0}]">{{item.change | Fixed2}}%</p>
              <p class="tr w30">{{item.volume}}</p>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapActions, mapGetters } from "vuex";
export default {
  name:'market',
  props:["quotationList"],
  data () {
    return {
      current:0,
      sortindex:'',
      direction:true,
      classtify:[{text:'币种',key:'at'},{text:'最新价',key:'now_price'},{text:'涨幅',key:'change'},{text:'24H成交量',key:'volume'}],
      quoList:[],
      selectedName:'',
      marketList:[],
      showMarket:false,
      socketData:{},
    };
  },
  computed: {
    ...mapState({
      tradeData: state => state.tradeData,
      nowPrice: state => state.nowPrice,
      rate: state => state.rate
    })
  },
  created(){
    if(window.localStorage.getItem('current')){
      this.current=window.localStorage.getItem('current');
    }
  },
  mounted(){
    this.getList();
    this.connect();
    // console.log(this.tradeData)
  },
  methods: {
    //父组件获取的币种列表
    getList(){
      var that = this;
      var msg = this.quotationList;
      console.log(msg)
      that.quoList=msg;
      var arr = [];
      for(var i=0;i<msg.length;i++){
        arr[i] = msg[i].quotation
      };
      var arrFrist=arr[0][0];
      that.marketList = arr; 
      let rate;
      if (!window.localStorage.getItem("tradeData")) {
        that.selectedName=arrFrist.legal_name;
        rate = that.quoList[0].fiat_convert_cny;
      }else{
        var localData=JSON.parse(window.localStorage.getItem("tradeData"));
        that.selectedName=localData.legal_name;
        rate = that.quoList[that.current].fiat_convert_cny;
      }
      that.$store.dispatch("rateChange",rate)
    },
    // 法币切换
    changeLegal(index,legalName){
      this.current=index;
      this.selectedName=legalName;
    },
    // 交易对切换
    change(legal_id,currency_id,legal_name,currency_name){
      let that = this;
      var tradeData = {
        legal_id:legal_id,
        currency_id: currency_id,
        legal_name: legal_name,
        currency_name: currency_name,
        symbol:currency_name+'/'+legal_name
      };
      var rate = that.quoList[that.current].fiat_convert_cny;
      that.$store.dispatch("rateChange",rate);
      this.showMarket=false;//关闭交易对弹窗
      //this.$store.commit('increment',tradeData);
      this.$store.dispatch("tradeChange",tradeData);//改变vuex的tradeData
      window.localStorage.setItem("tradeData", JSON.stringify(tradeData));//重新储存localStorage的tradeData
      window.localStorage.setItem('current',this.current);//储存当前法币的下标值(多币种要用到)
    },
    // socket时时通讯
    connect(){
      let that = this;
      that.$socket.emit("login", that.$makeSocketId());
      this.$socket.on("daymarket", msg => {
        if (msg.type == "daymarket") {
          if (that.selectedName && that.selectedName == msg.legal_name){
            // console.log(msg)
            if(msg.legal_id == that.tradeData.legal_id && msg.currency_id == that.tradeData.currency_id){//更新头部
              // console.log(that.tradeData.legal_name,that.tradeData.currency_name,msg.legal_name,msg.currency_name)
              that.socketData = msg;
              that.$store.dispatch("priceChange",msg.now_price)
            }
            that.marketList.forEach(function(item,index){
              var i = item.findIndex(function(ite,inde){
                return ite.currency_id == msg.currency_id&&ite.legal_id == msg.legal_id;
              })
              if(i != -1){
                item[i].now_price = msg.now_price;
                item[i].change = msg.change;
              }
            })
          }
        }
      });
    },
    updateData(msg){//原打算用首页的socket数据更新列表（store刷新会失联 已弃用）
      var that = this;
      if (that.selectedName && that.selectedName == msg.legal_name){
        that.marketList.forEach(function(item,index){
          var i = item.findIndex(function(ite,inde){
            return ite.currency_id == msg.currency_id&&ite.legal_id == msg.legal_id;
          })
          if(i != -1){
            item[i].now_price = msg.now_price;
            item[i].change = msg.change;
          }
        })
      }
    },
    // 数组排序
    sortData(index,key){
      this.direction=index===this.sortindex?!this.direction:false;
      this.sortindex=index;
      var k = key;
      var d = this.direction==true?'up':'down';
      this.marketList[this.current].sort(function(a,b){
        if(k == 'at'){
          if(d == 'up'){
            return a.currency_name.charCodeAt() - b.currency_name.charCodeAt()
          } else {
            return b.currency_name.charCodeAt() - a.currency_name.charCodeAt()
          }
        } else {
          if(d == 'up'){
            return a[k] - b[k];
          } else {
            return b[k] - a[k];
          }
        }
      })
    },
    // 自选
    addSelf(id){
      console.log(id)
    }
  }
}

</script>
<style lang='scss' scoped>
.market{
  position: relative;
  .tvTop{
    height: 48px;
    padding: 0 15px;
    .symbol{
      line-height: 32px;
      padding: 0 8px;
    }
    .symbol:hover{
      background: #2e3852;
    }
    .down-arrow{
      height: 16px;
      width: 16px;
      line-height: 18px;
    }
  }
  .chart_select{
    border-bottom: none;
  }
  .market_content{
    width: 460px;
    min-height: 400px;
    max-height: 534px;
    -webkit-box-shadow: 0 4px 16px rgba(69,97,137,.2);
    box-shadow: 0 4px 16px rgba(69,97,137,.2);
    top: 48px;
    left: 10px;
    bottom: 8px;
    z-index: 3;
    padding-bottom: 20px;
    position: absolute;
    overflow: inherit;
    transition: all 2s;
  
    .legalbox {
      padding: 0px 20px;
      p{
        height: 48px;
        line-height: 48px;
        margin-right: 10px;
      }
    }
    .coinbox{
      .classfity{
        padding: 0 10px;
        >div{
          // flex: 1;
          cursor: pointer;
          p{
            height: 25px;
            span{
              width: 0;
              height: 0;
              border-width: 5px;
              border-style: solid;
              margin-left: 10px;
            }
            .up{
              border-color: transparent transparent #4e5b85 transparent;
            }
            .down{
              border-color: #4e5b85 transparent transparent transparent;
            }
            .up.sort{
              border-color: transparent transparent #7a98f7 transparent;
            }
            .down.sort{
              border-color: #7a98f7 transparent transparent transparent;
            }
          }
        }
      }
      ul{
        max-height: 320px;
        overflow-y: scroll;
        li{
          div{
            height: 40px;
            line-height: 40px;
            padding: 0 10px;
            p{
              // flex:1;
            }
          }
          div:hover{
            background: #262a42;
          }
        }
      }
    }
  }
}
</style>
